﻿using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using NLog;

namespace Tzw.Common
{
    public class HttpHelper
    {
        public static string Request(string url, string data, string contentType = "application/json;")
        {
            var uri = new Uri(url);
            var webRequest = WebRequest.Create(uri);
            webRequest.ContentType = contentType;
            webRequest.Method = "POST";
            using (var requestStream = webRequest.GetRequestStream())
            {
                var paramBytes = Encoding.UTF8.GetBytes(data);
                requestStream.Write(paramBytes, 0, paramBytes.Length);
            }

            var webResponse = webRequest.GetResponse();
            using (var myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
            {
                return myStreamReader.ReadToEnd();
            }
        }

        /// <summary>
        /// 使用 GET 方式提交中文数据
        /// </summary>
        public static string HttpGet(string url)
        {
            var result = "";

            HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
            httpWebRequest.Method = "GET";

            if (httpWebRequest.GetResponse() is HttpWebResponse httpWebResponse)
            {
                using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }

                httpWebResponse.Close();
            }

            return result;
        }

    }
}